<template>
  <div class="courses-container">
    <div class="fixed-header">
      <van-nav-bar
        title="全部课程"
        left-arrow
        @click-left="onClickLeft"
      />
      
      <!-- 搜索框 -->
      <van-search
        v-model="searchValue"
        placeholder="搜索课程"
        show-action
        @search="onSearchSubmit"
        @focus="onSearchFocus"
        @cancel="onSearchCancel"
      />

      <!-- 搜索历史浮层 -->
      <div v-show="showHistory" class="search-history">
        <div class="history-header">
          <span>搜索历史</span>
          <van-icon name="delete-o" @click="clearHistory" />
        </div>
        <div class="history-list">
          <van-tag
            v-for="(item, index) in searchHistory"
            :key="index"
            plain
            type="primary"
            size="medium"
            class="history-item"
            @click="onHistoryClick(item)"
          >
            {{ item }}
          </van-tag>
        </div>
      </div>
    </div>

    <div class="content-area">
      <!-- 课程分类 -->
      <van-tabs v-model:active="activeTab" sticky swipeable>
        <van-tab v-for="category in categories" :key="category.id" :title="category.name">
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list
              v-model:loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <div class="course-list">
                <div v-for="course in courses" :key="course.id" class="course-card" @click="viewCourse(course)">
                  <van-image
                    :src="course.image"
                    class="course-image"
                    fit="cover"
                    radius="4"
                  />
                  <div class="course-info">
                    <div class="course-title">{{ course.name }}</div>
                    <div class="course-desc">{{ course.description }}</div>
                    <div class="course-meta">
                      <span class="course-duration">
                        <van-icon name="clock-o" />
                        {{ course.duration }}
                      </span>
                      <span class="course-students">
                        <van-icon name="friends-o" />
                        {{ course.students }}人学习
                      </span>
                    </div>
                    <div class="course-price">
                      <span class="price">¥{{ course.price }}</span>
                      <span class="original-price" v-if="course.originalPrice">¥{{ course.originalPrice }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </van-list>
          </van-pull-refresh>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'

const router = useRouter()

// 分类数据
const categories = ref([
  { id: 0, name: '全部' },
  { id: 1, name: '数学' },
  { id: 2, name: '英语' },
  { id: 3, name: '物理' },
  { id: 4, name: '化学' },
  { id: 5, name: '生物' },
  { id: 6, name: '语文' },
  { id: 7, name: '历史' },
  { id: 8, name: '地理' },
  { id: 9, name: '政治' },
  { id: 10, name: '信息技术' },
  { id: 11, name: '美术' },
  { id: 12, name: '音乐' },
  { id: 13, name: '体育' },
  { id: 14, name: '心理健康' }
])

// 列表状态
const activeTab = ref(0)
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const courses = ref([])
const currentPage = ref(1)
const pageSize = 10

// 搜索相关
const showSearch = ref(false)
const searchValue = ref('')
const searchHistory = ref([])
const showHistory = ref(false)
const searchLoading = ref(false)
const searchFinished = ref(false)
const searchResults = ref([])
const searchPage = ref(1)
const searchPageSize = 10

// 监听分类切换
watch(activeTab, () => {
  currentPage.value = 1
  courses.value = []
  finished.value = false
  loading.value = false
  onLoad()
})

// 模拟课程数据
const mockCourses = [
  {
    id: 1,
    name: '高中数学提高班 - 函数与导数专题',
    description: '针对高考重点难点，系统讲解函数与导数知识点',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '299.00',
    originalPrice: '399.00',
    duration: '120分钟',
    students: 2150,
    categoryId: 1
  },
  {
    id: 2,
    name: '英语口语训练营 - 零基础到流利表达',
    description: '从发音、语法到口语表达，全方位提升英语口语能力',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '399.00',
    originalPrice: '599.00',
    duration: '90分钟',
    students: 1832,
    categoryId: 2
  },
  {
    id: 3,
    name: 'Python编程基础 - 从入门到实践',
    description: '零基础入门Python编程，通过实践项目掌握编程思维',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '499.00',
    originalPrice: '699.00',
    duration: '150分钟',
    students: 968,
    categoryId: 1
  },
  {
    id: 4,
    name: '物理实验精讲 - 高中物理必修课程',
    description: '通过实验深入理解物理概念，掌握实验技能和方法',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '359.00',
    originalPrice: '459.00',
    duration: '180分钟',
    students: 756,
    categoryId: 3
  },
  {
    id: 5,
    name: '化学方程式专项训练',
    description: '系统梳理化学方程式，掌握配平技巧和应用',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '279.00',
    originalPrice: '379.00',
    duration: '100分钟',
    students: 1245,
    categoryId: 4
  },
  {
    id: 6,
    name: '生物知识点精讲 - 高考重点',
    description: '聚焦高考生物必考知识点，提供详细解析和练习',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '329.00',
    originalPrice: '429.00',
    duration: '160分钟',
    students: 892,
    categoryId: 5
  },
  {
    id: 7,
    name: '数学竞赛培训课程',
    description: '针对数学竞赛特训，提供高难度题目讲解和解题技巧',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '599.00',
    originalPrice: '799.00',
    duration: '200分钟',
    students: 468,
    categoryId: 1
  },
  {
    id: 8,
    name: '英语写作进阶课程',
    description: '从基础到高级，全面提升英语写作能力',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '449.00',
    originalPrice: '649.00',
    duration: '140分钟',
    students: 1056,
    categoryId: 2
  },
  {
    id: 9,
    name: '物理力学专题讲解',
    description: '深入讲解力学知识点，配合例题和习题训练',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '379.00',
    originalPrice: '479.00',
    duration: '170分钟',
    students: 825,
    categoryId: 3
  },
  {
    id: 10,
    name: '有机化学系统课程',
    description: '系统讲解有机化学知识，突破重点难点',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '459.00',
    originalPrice: '559.00',
    duration: '190分钟',
    students: 734,
    categoryId: 4
  },
  {
    id: 11,
    name: '生物实验技能训练',
    description: '掌握生物实验操作技能，提高实验分析能力',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '349.00',
    originalPrice: '449.00',
    duration: '150分钟',
    students: 567,
    categoryId: 5
  },
  {
    id: 12,
    name: '数学思维训练营',
    description: '培养数学思维，提升解题能力和创新思维',
    image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    price: '399.00',
    originalPrice: '499.00',
    duration: '160分钟',
    students: 1123,
    categoryId: 1
  }
]

// 模拟获取课程数据
const fetchCourses = async (page, categoryId) => {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 根据分类过滤课程
  let filteredCourses = [...mockCourses]
  if (categoryId > 0) {
    filteredCourses = mockCourses.filter(course => course.categoryId === categoryId)
  }
  
  // 模拟分页
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const hasMore = end < filteredCourses.length
  
  return {
    list: filteredCourses.slice(start, end),
    hasMore
  }
}

// 加载更多
const onLoad = async () => {
  try {
    if (refreshing.value) {
      currentPage.value = 1
      courses.value = []
      refreshing.value = false
    }

    const { list, hasMore } = await fetchCourses(currentPage.value, categories.value[activeTab.value].id)
    
    courses.value.push(...list)
    loading.value = false
    
    if (!hasMore) {
      finished.value = true
    } else {
      currentPage.value++
    }
  } catch (error) {
    console.error('加载课程失败:', error)
    showToast('加载失败，请重试')
    loading.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  finished.value = false
  loading.value = true
  currentPage.value = 1
  onLoad()
}

// 搜索相关方法
const onSearch = () => {
  showSearch.value = true
}

const resetSearch = () => {
  searchResults.value = []
  searchPage.value = 1
  searchFinished.value = false
  searchLoading.value = false
}

const onSearchSubmit = (value) => {
  if (!value.trim()) return
  
  // 更新搜索历史
  if (!searchHistory.value.includes(value)) {
    searchHistory.value.unshift(value)
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
  }

  // 重置搜索状态
  resetSearch()
  
  // 执行搜索
  searchCourses(value)
}

const searchCourses = (keyword) => {
  // 模拟搜索过滤
  const filteredCourses = mockCourses.filter(course => 
    course.name.toLowerCase().includes(keyword.toLowerCase()) ||
    course.description.toLowerCase().includes(keyword.toLowerCase())
  )
  
  // 模拟分页
  const start = (searchPage.value - 1) * searchPageSize
  const end = start + searchPageSize
  const pageResults = filteredCourses.slice(start, end)
  
  searchResults.value = [...searchResults.value, ...pageResults]
  searchLoading.value = false
  searchFinished.value = end >= filteredCourses.length
  
  if (pageResults.length > 0) {
    searchPage.value++
  }
}

const onSearchLoad = () => {
  if (searchFinished.value) return
  searchLoading.value = true
  setTimeout(() => {
    searchCourses(searchValue.value)
  }, 500)
}

const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('courseSearchHistory')
  showToast('已清空搜索历史')
}

// 查看课程详情
const viewCourse = (course) => {
  router.push(`/course/${course.id}`)
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 搜索框获得焦点
const onSearchFocus = () => {
  showHistory.value = true
}

// 取消搜索
const onSearchCancel = () => {
  searchValue.value = ''
  showHistory.value = false
}

// 点击历史记录
const onHistoryClick = (value) => {
  searchValue.value = value
  onSearchSubmit(value)
}

// 保存搜索历史
const saveSearchHistory = (value) => {
  if (!value.trim() || searchHistory.value.includes(value)) {
    return
  }
  
  searchHistory.value.unshift(value)
  if (searchHistory.value.length > 10) {
    searchHistory.value.pop()
  }
  
  // 保存到本地存储
  localStorage.setItem('courseSearchHistory', JSON.stringify(searchHistory.value))
}

// 加载搜索历史
const loadSearchHistory = () => {
  const history = localStorage.getItem('courseSearchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
}

// 在组件挂载时加载搜索历史
onMounted(() => {
  loadSearchHistory()
})
</script>

<style lang="scss" scoped>
@use '../../styles/mixins.scss' as mixins;

.courses-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;

  .fixed-header {
    position: relative;
    z-index: 99;
    background-color: #fff;
  }

  .content-area {
    flex: 1;
    overflow-y: auto;

    :deep(.van-tabs) {
      .van-tabs__wrap {
        height: 44px;
      }

      .van-tabs__nav {
        padding: 0 12px;
        background: #fff;
      }

      .van-tab {
        flex: 0 0 auto;
        padding: 0 16px;
        font-size: 14px;
        color: #666;
        position: relative;

        &--active {
          color: var(--van-primary-color);
          font-weight: 500;
        }

        &::before {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          width: 0;
          height: 3px;
          background-color: var(--van-primary-color);
          transition: all 0.3s;
          transform: translateX(-50%);
        }

        &--active::before {
          width: 20px;
        }
      }

      .van-tabs__line {
        display: none;
      }
    }
  }

  .search-history {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background-color: #fff;
    z-index: 999;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .history-header {
      @include mixins.flex(row, space-between);
      margin-bottom: 12px;
      color: #666;
      font-size: 14px;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .history-item {
        margin-right: 8px;
        margin-bottom: 8px;
      }
    }
  }

  .course-list {
    padding: 12px;
  }

  .course-card {
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 12px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);

    .course-image {
      width: 100%;
      height: 160px;
    }

    .course-info {
      padding: 12px;

      .course-title {
        font-size: 16px;
        font-weight: 500;
        color: #323233;
        margin-bottom: 8px;
        @include mixins.text-ellipsis;
      }

      .course-desc {
        font-size: 14px;
        color: #969799;
        margin-bottom: 8px;
        @include mixins.text-ellipsis-multi(2);
      }

      .course-meta {
        @include mixins.flex(row, flex-start);
        font-size: 12px;
        color: #969799;
        margin-bottom: 8px;

        .course-duration,
        .course-students {
          @include mixins.flex(row, flex-start);

          .van-icon {
            margin-right: 4px;
          }
        }

        .course-students {
          margin-left: 16px;
        }
      }

      .course-price {
        @include mixins.flex(row, flex-start);
        align-items: baseline;

        .price {
          font-size: 18px;
          font-weight: 500;
          color: #ee0a24;
        }

        .original-price {
          font-size: 14px;
          color: #969799;
          text-decoration: line-through;
          margin-left: 8px;
        }
      }
    }
  }
}
</style>
